package com.hsy.crm.web.service.impl.excel;

import com.hsy.crm.web.domain.cm.App;
import com.hsy.crm.web.domain.entity.Product;
import com.hsy.crm.web.domain.entity.ProductMultiUnit;
import com.hsy.crm.web.domain.entity.ProductPrice;
import com.hsy.crm.web.domain.entity.ProductType;
import com.hsy.crm.web.domain.entity.Unit;
import com.hsy.crm.web.domain.po.product.ProductExportPo;
import com.hsy.crm.web.domain.vo.report.ExcelVo;
import com.hsy.crm.web.mapper.ProductMultiUnitMapper;
import com.hsy.crm.web.mapper.ProductPriceMapper;
import com.hsy.crm.web.service.impl.ProductService;
import com.hsy.crm.web.service.impl.ProductTypeService;
import com.hsy.crm.web.service.impl.UnitService;
import com.hsy.crm.web.utils.CalcUtils;
import com.hsy.crm.web.utils.RegularUtils;
import com.hsy.crm.web.utils.StringUtils;
import com.hsy.crm.web.utils.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EProductService{


    private static String XG = "/";

    @Autowired
    ProductService productService;

    @Autowired
    ProductTypeService productTypeService;

    @Autowired
    UnitService unitService;

    @Autowired
    ProductMultiUnitMapper productMultiUnitMapper;

    @Autowired
    ProductPriceMapper productPriceMapper;

    /**
     * product
     * productType
     * unit
     * productPrice
     * @param products
     * @param product
     */
    @Transactional
    public void insertProducts(List<ProductExportPo> products, Product product){
        for (ProductExportPo productExportPo : products){
            //调用顺序不可变
            ProductType productType = doProducTypes(productExportPo,product);

            if( productType == null ){
                continue;
            }
            productExportPo.setProductTypeId(productType.getId());
            if ( doProduct(productExportPo,product) ) {
                doUnits(productExportPo,product);
                doProductPrice(productExportPo,product);
            }
        }
    }

    public void doProductPrice(ProductExportPo productExportPo,Product product){
        ProductPrice productPrice = new ProductPrice();
        productPrice.setPrice1(CalcUtils.mul_price(productExportPo.getPrice1()).longValue());
        productPrice.setPrice2(CalcUtils.mul_price(productExportPo.getPrice2()).longValue());
        productPrice.setPrice3(CalcUtils.mul_price(productExportPo.getPrice3()).longValue());
        productPrice.setPrice4(CalcUtils.mul_price(productExportPo.getPrice4()).longValue());
        productPrice.setPrice5(CalcUtils.mul_price(productExportPo.getPrice5()).longValue());
        productPrice.setProductId(product.getId());
        productPrice.setCustomerId(product.getCustomerId());
        productPrice.setId(UuidUtils.getUuid());
        productPriceMapper.insert(productPrice);
    }

    public void doUnits(ProductExportPo productExportPo,Product product){
        String unitNames = productExportPo.getUnitName();
        String unitRates = productExportPo.getUnitRates();

        if( StringUtils.isEmpty(unitNames) ){
            return;
        }

        String[] unitNamesArr = unitNames.split(XG);
        String[] unitRatesArr = null;
        if( !StringUtils.isEmpty(unitRates) ){
            unitRatesArr = unitRates.split(XG);
        }

        if( unitRatesArr != null && unitNamesArr.length != unitRatesArr.length ){
            return;
        }

        for( int i=0 ; i<unitNamesArr.length ; i++ ){
            if( i == 0 ){
                doUnit(unitNamesArr[i],null,product,i);
            }else{
                doUnit(unitNamesArr[i],unitRatesArr[i],product,i);
            }
        }
    }

    public void doUnit(String unitName,String unitRate,Product product,int index){

        Unit unit = new Unit();
        unit.setName(unitName);
        unit.setCustomerId(product.getCustomerId());
        unit.setLoginCompanyId(product.getLoginCompanyId());
        unit.setLoginUserId(product.getLoginUserId());
        unit.setCompanyId(product.getLoginCompanyId());
        Unit unitDb = unitService.selectOne(unit);
        if( unitDb == null ){
            int unitType = index == 0?1:2;
            unit.setType(unitType);
            unitService.insert(unit);
        }

        Long unitId = unitDb == null ? unit.getId() : unitDb.getId();
        if( index > 0 ){
            // 辅单位

            if( !RegularUtils.isNumeric(unitRate) ){
                return;
            }

            ProductMultiUnit multiUnit = new ProductMultiUnit();
            multiUnit.setProductId(product.getId());
            multiUnit.setRate(Integer.parseInt(unitRate));
            multiUnit.setUnitId(unitId);
            multiUnit.setCustomerId(product.getCustomerId());
            multiUnit.setId(UuidUtils.getUuid());
            productMultiUnitMapper.insert(multiUnit);
        }else{
            if( product.getId() == null ){
                return;
            }
            Product productUnit = new Product();
            productUnit.setId(product.getId());
            productUnit.setUnitId(unitId);
            productUnit.setCustomerId(product.getCustomerId());
            productUnit.setLoginCompanyId(product.getLoginCompanyId());
            productUnit.setLoginUserId(product.getLoginUserId());
            productUnit.setCompanyId(product.getLoginCompanyId());
            productService.update(productUnit);
        }

    }

    private ProductType doProducTypes(ProductExportPo productExportPo,Product product){
        String productTypeNames = productExportPo.getProductTypeNames();
        if(StringUtils.isEmpty(productTypeNames)){
            return null;
        }

        String[] producTypes = productExportPo.getProductTypeNames().split(XG);

        String productName = "";
        ProductType lastProducType = null;
        for (String producType : producTypes){
            productName =  productName.length() == 0 ? producType : productName +XG+ producType;
            lastProducType = this.doProducType(product,productName);
        }
        return lastProducType;
    }

    private ProductType doProducType(Product product,String producTypeName){
        ProductType productType = new ProductType();
        productType.setName(producTypeName);
        productType.setCustomerId(product.getCustomerId());
        productType.setLoginCompanyId(product.getLoginCompanyId());
        productType.setLoginUserId(product.getLoginUserId());
        productType.setCompanyId(product.getLoginCompanyId());
        ProductType productTypeDb = productTypeService.selectOne(productType);
        if( productTypeDb == null ){
            productTypeService.insertProductType(productType);
            return productType;
        }else {
            return productTypeDb;
        }
    }

    private boolean doProduct(ProductExportPo productExportPo,Product product){

        if( !checkProduct(productExportPo,product) ){
            return false;
        }

        productExportPo.setCustomerId(product.getCustomerId());
        productExportPo.setLoginCompanyId(product.getLoginCompanyId());
        productExportPo.setLoginUserId(product.getLoginUserId());
        productExportPo.setCompanyId(product.getLoginCompanyId());
        productExportPo.setPurchasePrice(App.DECIMAL.DIV);

        // 数据转换
        productExportPo.setPurchasePrice(CalcUtils.mul_price(productExportPo.getPurchaseRealPrice()).longValue());
        productExportPo.setSalePrice(CalcUtils.mul_price(productExportPo.getSaleRealPrice()).longValue());

        //空默认否  非否非是默认否
        if( StringUtils.isEmpty(productExportPo.getEnableBatchs()) || productExportPo.getEnableBatchs().equals(App.Booleans.isNo()) ){
            productExportPo.setEnableBatch(App.Booleans.NO);
        }else{
            productExportPo.setEnableBatch(App.Booleans.YES);
        }

        if( StringUtils.isEmpty(productExportPo.getEnableStores()) || productExportPo.getEnableStores().equals(App.Booleans.isNo()) ){
            productExportPo.setEnableStore(App.Booleans.NO);
        }else{
            productExportPo.setEnableStore(App.Booleans.YES);

            String[] stores = productExportPo.getEnableStores().split(XG);
            if( stores.length > 1 && RegularUtils.isNumeric(stores[1]) ){
                productExportPo.setStoreMin(Integer.parseInt(stores[1]));
            }
            if( stores.length > 2 && RegularUtils.isNumeric(stores[2]) ){
                productExportPo.setStoreMax(Integer.parseInt(stores[2]));
            }
        }

        if ( StringUtils.isEmpty(productExportPo.getEnableFines()) || productExportPo.getEnableFines().equals(App.Booleans.isNo()) ){
            productExportPo.setEnableFine(App.Booleans.NO);
        }else{
            productExportPo.setEnableFine(App.Booleans.YES);

            String[] fines = productExportPo.getEnableFines().split(XG);
            if( fines.length > 1 && RegularUtils.isNumeric(fines[1]) ){
                productExportPo.setFineDays(Integer.parseInt(fines[1]));
            }
            if( fines.length > 2 && RegularUtils.isNumeric(fines[2]) ){
                productExportPo.setWarnDays(Integer.parseInt(fines[2]));
            }
        }

        productService.insert(productExportPo);
        product.setId(productExportPo.getId());

        return true;
    }

    private boolean checkProduct(ProductExportPo productExportPo,Product product){
        Product selectProduct = new Product();

        selectProduct.setCustomerId(product.getCustomerId());
        selectProduct.setLoginCompanyId(product.getLoginCompanyId());
        selectProduct.setLoginUserId(product.getLoginUserId());
        selectProduct.setCompanyId(product.getLoginCompanyId());

        selectProduct.setName(productExportPo.getName());
        Product tmp = productService.selectOne(selectProduct);
        if( tmp != null ){
            return false;
        }

        selectProduct.setName(null);
        selectProduct.setCode(productExportPo.getCode());
        tmp = productService.selectOne(selectProduct);
        if( tmp != null ){
            return false;
        }

        if( !StringUtils.isEmpty(productExportPo.getBarcode()) ){
            selectProduct.setCode(null);
            selectProduct.setBarcode(productExportPo.getBarcode());
            tmp = productService.selectOne(selectProduct);
            if( tmp != null ){
                return false;
            }
        }

        return true;
    }



    public List<ProductExportPo> findProductData(ExcelVo excelVo){
        List<ProductExportPo> data = productService.findProductData(excelVo);

        for( ProductExportPo product : data ){

            product.setPurchaseRealPrice(CalcUtils.div_price(product.getPurchaseRealPrice()));
            product.setSaleRealPrice(CalcUtils.div_price(product.getSaleRealPrice()));
            if(product.getPrice1()!=null)product.setPrice1(CalcUtils.div_price(product.getPrice1()));
            if(product.getPrice2()!=null)product.setPrice2(CalcUtils.div_price(product.getPrice2()));
            if(product.getPrice3()!=null)product.setPrice3(CalcUtils.div_price(product.getPrice3()));
            if(product.getPrice4()!=null)product.setPrice4(CalcUtils.div_price(product.getPrice4()));
            if(product.getPrice5()!=null)product.setPrice5(CalcUtils.div_price(product.getPrice5()));

            if(product.getEnableBatch()== App.Booleans.YES){
                product.setEnableBatchs(App.Booleans.isYes());
            }else{
                product.setEnableBatchs(App.Booleans.isNo());
            }

            if(product.getEnableFine()== App.Booleans.YES){
                product.setEnableFines(App.Booleans.isYes()+XG+product.getFineDays()+XG+product.getWarnDays());
            }else{
                product.setEnableFines(App.Booleans.isNo());
            }

            if(product.getEnableStore()== App.Booleans.YES){
                product.setEnableStores(App.Booleans.isYes()+XG+product.getStoreMin()+XG+product.getStoreMax());
            }else{
                product.setEnableStores(App.Booleans.isNo());
            }

            if( product.getUnitNameRates()!=null ){
                setNameRates(product);
            }
        }

        return data;
    }

    private void setNameRates(ProductExportPo product){
        product.setUnitRates("1");
        String[] units = product.getUnitNameRates().split(",");
        for( String unit : units ){
            String[] us = unit.split("/");
            product.setUnitName(product.getUnitName()+"/"+us[0]);
            product.setUnitRates(product.getUnitRates()+"/"+us[1]);
        }
    }

}
